iT邦幫忙

2026 iThome 鐵人賽

DAY 6
0

變數可以讓程式記住資料,後面使用這個名稱就能找到他代表的值。JavaScript常用let和const來建立變數。

let a=1;
const b=2;

console.log(a);
console.log(b);

https://ithelp.ithome.com.tw/upload/images/20260920/20178696t57uNzbQtK.png
以下是兩種宣告方式的差別

const:用const宣告的化後面不能重新宣告也不能重新賦值,適合不會改變的資料。
let:let之後還能重新賦值但不能重新宣告,適合會跟著操作改變的資料。

let a=1;
a=2;

console.log(a);

https://ithelp.ithome.com.tw/upload/images/20260920/20178696SYMLaPytZe.png
用let的話可以看到成功的將a改成了2,但是如果宣告的方式是用const 的話就會出現錯誤

const a=1;
a=2;

console.log(a);

https://ithelp.ithome.com.tw/upload/images/20260920/20178696GI6SjL8Kkr.png

剩下的還有一種舊的宣告方式叫var,既能重新宣告也能重新賦值
用let重新宣告的結果

let a=10;
let a=20;

https://ithelp.ithome.com.tw/upload/images/20260920/20178696NGHmFY8BS8.png
用var的話就不會有問題

var a=10;
console.log(a);
var a=20;
console.log(a);
a =30;
console.log(a);

https://ithelp.ithome.com.tw/upload/images/20260920/20178696hKLJjN0nWU.png


上一篇
day5資料型別
下一篇
day7 if else
系列文
從頭開始的Javascript學習之旅9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言